package com.juzipi.demo.singleton.type6;

public class SingletonTest6 {

    public static void main(String[] args) {
        //双重检查
        Singleton instance = Singleton.getInstance();
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance.hashCode());
        System.out.println(instance1.hashCode());
        System.out.println(instance.equals(instance1));
        System.out.println(instance == instance1);
    }

}

//双重检查，线程安全,同步代码块
class Singleton{
    private static volatile Singleton instance;

    private Singleton(){

    }
    //提供一个静态的公有方法，加入了双重检查代码块，解决线程安全问题，同时解决懒加载问题
    //同时保证了效率
    public static Singleton getInstance(){
        //双重if判断
        if (instance == null){
            synchronized (Singleton.class){
                if (instance == null){
                    instance = new Singleton();
                }
            }

        }
        return instance;
    }

}
